#include "render_system/texture.h"

#include <CImg/CImg.h>

#include "render_system/gl_header.h"
#include "utility.h"

void Texture::_create(const std::string& fileName)
{
    using namespace cimg_library;
    try
    {
        CImg<unsigned char> img(fileName.c_str());

        // Copy file to OpenGL
        glActiveTexture(GL_TEXTURE0);
        GLuint tid;
        glGenTextures(1, &tid);
        glBindTexture(GL_TEXTURE_2D, tid);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.width(), 
            img.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, 
            img.data());
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, 
            GL_LINEAR);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, 
            GL_LINEAR);
        // Set the Tex1 sampler uniform to refer to texture unit 0
        int loc(0);
        if( loc >= 0 )
            glUniform1i(loc, 0);
        else
            fprintf(stderr, "Uniform variable Tex1 not found!\n");

    }
    catch(const std::exception& e)
    {
        Log::error(e.what());
        throw;
    }
}

